package com.kajespero.json.Converter;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import com.kajespero.json.annotation.JSonKind;
import com.kajespero.json.helper.ClassHelper;
import com.kajespero.json.process.JSonMappingProcess;

public class JSonConverter {

	@SuppressWarnings("unchecked")
	public static <E>  Collection<E> fromJSon(Map<?, ?> map, Class<E> dto){
		
		JSonKind kind = JSonMappingProcess.getKind(dto);

		String className = dto.getSimpleName();
		System.out.println("test class fromJSon " + className);
		if(kind != null){
			if(!kind.name().isEmpty()){
				className = kind.name();
			}
		}
		Collection<Map<?, ?>> array = (Collection<Map<?, ?>>) map.get(className);
		List<E> list = new ArrayList<E>();
		if(array != null){
			for(Map<?, ?> mapArray : array){
				System.out.println("test class " + dto);
				E instance = ClassHelper.newInstance(dto);
				for(Object key : mapArray.keySet()){
					JSonMappingProcess.setInstance(instance, key.toString(), mapArray.get(key));
				}
				list.add(instance);
			}
		}
		return list;
	}
	
	public static <E> E fromJSonObject(Map<?, ?> map, Class<E> dto){
		JSonKind kind = JSonMappingProcess.getKind(dto);

		String className = dto.getSimpleName();
		System.out.println("test class fromJSon " + className);
		if(kind != null){
			if(!kind.name().isEmpty()){
				className = kind.name();
			}
		}
		Map<?, ?> values = (Map<?, ?>) map.get(className);
		E instance = ClassHelper.newInstance(dto);
		for(Object key : values.keySet()){
			JSonMappingProcess.setInstance(instance, key.toString(), values.get(key));
		}
		return instance;
	}
}
